package com.wzt.car.service.impl;

import com.wzt.base.util.PageResult;
import com.wzt.car.es.doc.CarDoc;
import com.wzt.car.es.repository.CarDocRepository;
import com.wzt.car.query.CarSearchQuery;
import com.wzt.car.service.ICarSearchService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Zenith
 */
@Service
public class CarSearchServiceImpl implements ICarSearchService {
    @Autowired
    private CarDocRepository repository;

    @Override
    public PageResult<CarDoc> search(CarSearchQuery searchQuery) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.高级查询
        builder.withQuery(boolQuery);

        // 2.排序
        // 2.1获取排序字段和类型
        String orderField = searchQuery.getOrderField();
        String orderType = searchQuery.getOrderType();
        // 2.2默认使用价格排序
        orderField = orderField == null ? "jg" : orderField;
        // 2.3排序条件处理
        SortOrder sortOrder = SortOrder.DESC;
        // 排序类型
        if ("asc".equals(orderType)) {
            sortOrder = SortOrder.ASC;
        }
        // 价格
        if ("jg".equals(orderField)) {
            builder.withSort(SortBuilders.fieldSort("costprice").order(sortOrder));
        }
        // 车龄
        if ("cl".equals(orderField)) {
            builder.withSort(SortBuilders.fieldSort("reigstertime").order(sortOrder));
        }
        // 里程
        if ("lc".equals(orderField)) {
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));
        }
        // 最新上架时间
        if ("no".equals(orderField)) {
            builder.withSort(SortBuilders.fieldSort("onsaletime").order(sortOrder));
        }

        // 3.分页
        builder.withPageable(PageRequest.of(searchQuery.getStart(), searchQuery.getPageSize()));

        // 4.封装查询结果
        Page<CarDoc> result = repository.search(builder.build());
        List<CarDoc> content = result.getContent();
        Long total = result.getTotalElements();
        return new PageResult<>(content, total, null);
    }
}
